<template>
	<view class="new-product-list">
		<!-- 页面头部：标题+搜索 -->
		<view class="page-header">
			<text class="header-title">新品管理</text>
			<!-- 搜索栏 -->
			<view class="search-container">
				<uni-icons class="search-icon" type="search" size="24" color="#999" />
				<input class="search-input" v-model="searchKeyword" placeholder="搜索商品名称/条码" @input="handleSearch" @blur="hideKeyboard" />
			</view>
		</view>

		<!-- 筛选栏：分类+状态 -->
		<view class="filter-bar">
			<!-- 分类筛选 -->
			<view class="filter-item">
				<text class="filter-label">分类：</text>
				<picker mode="selector" :range="categoryList" :range-key="'name'" @change="handleCategoryChange" class="filter-picker">
					<view class="picker-content">
						{{ selectedCategory.name || '全部分类' }}
						<uni-icons type="down" size="20" color="#666" />
					</view>
				</picker>
			</view>

			<!-- 状态筛选 -->
			<view class="filter-item">
				<text class="filter-label">状态：</text>
				<picker mode="selector" :range="statusList" @change="handleStatusChange" class="filter-picker">
					<view class="picker-content">
						{{ selectedStatus.label }}
						<uni-icons type="down" size="20" color="#666" />
					</view>
				</picker>
			</view>
		</view>

		<!-- 列表空状态 -->
		<view class="empty-state" v-if="filteredProductList.length === 0">
			<uni-icons type="empty" size="80" color="#ccc" />
			<text class="empty-text">暂无新品数据</text>
			<button class="add-btn" @click="navigateToCreate">+ 新建商品</button>
		</view>

		<!-- 新品列表 -->
		<view class="product-list-container" v-else>
			<view class="product-item" v-for="(product, index) in filteredProductList" :key="product.id || index" @click="navigateToDetail(product)">
				<!-- 商品图片 -->
				<view class="product-img-wrapper">
					<image class="product-img" :src="(product.photo && product.photo[0].url) || '/static/default-goods.png'" mode="aspectFill" />
					<!-- 商品状态标签 -->
					<view class="product-status-tag" :class="product.status === 1 ? 'status-on' : 'status-off'">
						{{ product.status === 1 ? '已上架' : '待上架' }}
					</view>
				</view>

				<!-- 商品信息 -->
				<view class="product-info">
					<!-- 商品名称（取主名称） -->
					<text class="product-name">
						{{ (product.goodName && product.goodName[0].goodName) || '未命名商品' }}
					</text>

					<!-- 商品别名（最多显示2个） -->
					<view class="product-alias" v-if="product.goodName && product.goodName.length > 1">
						<text class="alias-label">别名：</text>
						<text class="alias-text">
							{{
								product.goodName
									.slice(1, 3)
									.map((item) => item.goodName)
									.join(' / ') + (product.goodName.length > 3 ? '...' : '')
							}}
						</text>
					</view>

					<!-- 基础属性：单位+条码 -->
					<view class="product-props">
						<view class="prop-item">
							<text class="prop-label">单位：</text>
							<text class="prop-value">
								{{ (product.unit && product.unit[0].unitName) || '未设置' }}
							</text>
						</view>
						<view class="prop-item">
							<text class="prop-label">条码：</text>
							<text class="prop-value">
								{{ (product.barcode && product.barcode[0]) || '未设置' }}
							</text>
						</view>
					</view>

					<!-- 规格+储存要求 -->
					<view class="product-extra">
						<view class="extra-item">
							<text class="extra-label">规格：</text>
							<text class="extra-value">
								{{ product.specs && product.specs.length > 0 ? product.specs.map((item) => item.specs).join('、') : '无规格' }}
							</text>
						</view>
						<view class="extra-item">
							<text class="extra-label">储存：</text>
							<text class="extra-value">{{ product.temperature || '常温(10-30度)' }}</text>
						</view>
					</view>
				</view>

				<!-- 操作区 -->
				<view class="product-actions">
					<button class="action-btn edit-btn" @click.stop="navigateToEdit(product)">编辑</button>
					<button class="action-btn status-btn" :class="product.status === 1 ? 'status-off-btn' : 'status-on-btn'" @click.stop="toggleProductStatus(product)">
						{{ product.status === 1 ? '下架' : '上架' }}
					</button>
				</view>
			</view>
		</view>

		<!-- 新建商品悬浮按钮 -->
		<view class="add-product-btn" @click="navigateToCreate">
			<uni-icons type="plus" size="32" color="#fff" />
			<text class="btn-text">新建商品</text>
		</view>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
export default {
	data() {
		return {
			// 搜索筛选
			searchKeyword: '',
			// 分类筛选
			categoryList: [
				{ id: '', name: '全部分类' },
				{ id: '1', name: '食品生鲜' },
				{ id: '2', name: '日用百货' },
				{ id: '3', name: '数码家电' },
				{ id: '4', name: '服装鞋帽' }
			],
			selectedCategory: {},
			// 状态筛选
			statusList: [
				{ value: '', label: '全部状态' },
				{ value: '1', label: '已上架' },
				{ value: '0', label: '待上架' }
			],
			selectedStatus: { value: '', label: '全部状态' },
			// 商品列表数据（与新建商品表单结构匹配）
			productList: [],
			// 筛选后列表
			filteredProductList: []
		};
	},
	onLoad() {
		// 页面加载时获取新品列表
	//	this.getProductList();
	},
	methods: {
		// 获取商品列表（模拟接口请求）
		async getProductList() {
			try {
				//uni.showLoading({ title: '加载中...' });
				// 从数据库获取商品数据（与新建商品的collection一致）
				const { data: res } = await db.collection('product').where({
					create_user:this.$store.state.msg.user.userId
				}).get();

				// 为商品数据补充默认状态（待上架）
				this.productList = res.map((item) => ({
					...item,
					id: item._id || item.id, // 兼容数据库_id和自定义id
					status: item.status ?? 0 // 0=待上架，1=已上架
				}));

				// 初始筛选（全部数据）
				this.filteredProductList = [...this.productList];
			} catch (error) {
				console.error('获取商品列表失败:', error);
				uni.showToast({ title: '加载失败，请重试', icon: 'none' });
				this.productList = [];
				this.filteredProductList = [];
			} finally {
				uni.hideLoading();
			}
		},

		// 搜索筛选
		handleSearch() {
			const keyword = this.searchKeyword.trim().toLowerCase();
			if (!keyword) {
				this.filteredProductList = [...this.productList];
				return;
			}

			// 按商品名称、别名、条码搜索
			this.filteredProductList = this.productList.filter((product) => {
				// 匹配商品名称
				const matchName = product.goodName?.some((item) => item.goodName.toLowerCase().includes(keyword)) || false;

				// 匹配条码
				const matchBarcode = product.barcode?.some((code) => code.toLowerCase().includes(keyword)) || false;

				return matchName || matchBarcode;
			});
		},

		// 分类筛选
		handleCategoryChange(e) {
			const index = e.detail.value;
			this.selectedCategory = this.categoryList[index];

			// 筛选分类（此处假设商品有categoryId字段，需与实际数据匹配）
			this.filteredProductList = this.productList.filter((product) => {
				return this.selectedCategory.id === '' ? true : product.categoryId === this.selectedCategory.id;
			});
		},

		// 状态筛选
		handleStatusChange(e) {
			const index = e.detail.value;
			this.selectedStatus = this.statusList[index];

			// 筛选状态
			this.filteredProductList = this.productList.filter((product) => {
				return this.selectedStatus.value === '' ? true : product.status === Number(this.selectedStatus.value);
			});
		},

		// 切换商品状态（上架/下架）
		async toggleProductStatus(product) {
			const newStatus = product.status === 1 ? 0 : 1;
			const statusText = newStatus === 1 ? '上架' : '下架';

			try {
				uni.showLoading({ title: `正在${statusText}...` });

				// 更新数据库状态
				await db.collection('sendgood').doc(product.id).update({ status: newStatus });

				// 更新本地列表状态
				const index = this.productList.findIndex((item) => item.id === product.id);
				if (index !== -1) {
					this.productList[index].status = newStatus;
					// 同步更新筛选后列表
					this.handleSearch();
				}

				uni.showToast({ title: `${statusText}成功`, icon: 'success' });
			} catch (error) {
				console.error(`${statusText}商品失败:", error`);
				uni.showToast({ title: `${statusText}失败，请重试`, icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},

		// 跳转到商品详情页
		navigateToDetail(product) {
			uni.navigateTo({
				url: `/pages/productDetail/productDetail?id=${product.id}`,
				fail: () => {
					uni.showToast({ title: '打开详情页失败', icon: 'none' });
				}
			});
		},

		// 跳转到编辑商品页（复用新建商品表单）
		navigateToEdit(product) {
			// 将商品数据转为JSON字符串传递（避免数据丢失）
			const productStr = encodeURIComponent(JSON.stringify(product));
			uni.navigateTo({
				url: `/pages/createProduct/createProduct?type=edit&product=${productStr}`,
				fail: () => {
					uni.showToast({ title: '打开编辑页失败', icon: 'none' });
				}
			});
		},

		// 跳转到新建商品页
		navigateToCreate() {
			uni.navigateTo({
				url: `/pages/createProduct/createProduct?type=create`,
				fail: () => {
					uni.showToast({ title: '打开新建页失败', icon: 'none' });
				}
			});
		},

		// 隐藏键盘
		hideKeyboard() {
			uni.hideKeyboard();
		}
	}
};
</script>

<style lang="scss" scoped>
/* 全局变量 */
$color-primary: #007aff;
$color-success: #07c160;
$color-warning: #ff976a;
$color-danger: #f53f3f;
$color-gray-100: #f8f8f8;
$color-gray-200: #eee;
$color-gray-300: #ccc;
$color-gray-600: #666;
$color-gray-900: #333;
$border-radius: 12rpx;
$shadow-sm: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

.new-product-list {
	background-color: $color-gray-100;
	min-height: 100vh;
	padding-bottom: 140rpx; // 预留底部按钮空间
}

/* 页面头部 */
.page-header {
	padding: 20rpx 30rpx;
	background-color: #fff;
	box-shadow: $shadow-sm;

	.header-title {
		display: block;
		font-size: 32rpx;
		font-weight: 600;
		color: $color-gray-900;
		margin-bottom: 20rpx;
	}

	.search-container {
		display: flex;
		align-items: center;
		background-color: $color-gray-100;
		border-radius: 60rpx;
		padding: 0 24rpx;
		height: 60rpx;

		.search-icon {
			margin-right: 16rpx;
		}

		.search-input {
			flex: 1;
			height: 100%;
			font-size: 26rpx;
			color: $color-gray-900;

			&::placeholder {
				color: $color-gray-300;
			}
		}
	}
}

/* 筛选栏 */
.filter-bar {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid $color-gray-200;

	.filter-item {
		display: flex;
		align-items: center;
		gap: 12rpx;

		.filter-label {
			font-size: 26rpx;
			color: $color-gray-600;
		}

		.filter-picker {
			background-color: $color-gray-100;
			border-radius: 40rpx;
			padding: 0 20rpx;
			height: 56rpx;
			display: flex;
			align-items: center;
			min-width: 180rpx;
		}

		.picker-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 26rpx;
			color: $color-gray-900;
		}
	}
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 500rpx;
	color: $color-gray-300;

	.empty-text {
		font-size: 28rpx;
		margin: 30rpx 0;
		color: $color-gray-600;
	}

	.add-btn {
		background-color: $color-primary;
		color: #fff;
		border-radius: 40rpx;
		padding: 0 40rpx;
		height: 64rpx;
		font-size: 26rpx;
	}
}

/* 商品列表容器 */
.product-list-container {
	padding: 20rpx 30rpx;
}

/* 商品项 */
.product-item {
	display: flex;
	gap: 20rpx;
	background-color: #fff;
	border-radius: $border-radius;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: $shadow-sm;
	transition: all 0.2s ease;

	&:active {
		transform: scale(0.99);
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}
}

/* 商品图片 */
.product-img-wrapper {
	position: relative;
	width: 160rpx;
	height: 160rpx;
	flex-shrink: 0;
	border-radius: 8rpx;
	overflow: hidden;

	.product-img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.product-status-tag {
		position: absolute;
		top: 12rpx;
		right: 12rpx;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		font-size: 20rpx;
		color: #fff;
		font-weight: 500;

		&.status-on {
			background-color: $color-success;
		}

		&.status-off {
			background-color: $color-gray-300;
		}
	}
}

/* 商品信息 */
.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	gap: 12rpx;
}

.product-name {
	font-size: 28rpx;
	color: $color-gray-900;
	font-weight: 500;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1;
	overflow: hidden;
}

.product-alias {
	display: flex;
	align-items: center;
	gap: 8rpx;
	font-size: 24rpx;
	color: $color-gray-600;

	.alias-label {
		color: $color-gray-300;
	}

	.alias-text {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}
}

.product-props {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	font-size: 24rpx;
	color: $color-gray-600;

	.prop-item {
		display: flex;
		align-items: center;
		gap: 8rpx;

		.prop-label {
			color: $color-gray-300;
		}
	}
}

.product-extra {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	font-size: 24rpx;
	color: $color-gray-600;

	.extra-item {
		display: flex;
		align-items: center;
		gap: 8rpx;

		.extra-label {
			color: $color-gray-300;
		}
	}
}

/* 操作区 */
.product-actions {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	flex-shrink: 0;
	width: 140rpx;
}

.action-btn {
	height: 56rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;

	&.edit-btn {
		background-color: $color-gray-100;
		color: $color-gray-900;
	}

	&.status-btn {
		color: #fff;

		&.status-on-btn {
			background-color: $color-success;
		}

		&.status-off-btn {
			background-color: $color-danger;
		}
	}
}

/* 新建商品悬浮按钮 */
.add-product-btn {
	position: fixed;
	right: 30rpx;
	bottom: 30rpx;
	display: flex;
	align-items: center;
	gap: 12rpx;
	background-color: $color-primary;
	color: #fff;
	border-radius: 60rpx;
	padding: 0 30rpx;
	height: 80rpx;
	font-size: 28rpx;
	font-weight: 500;
	box-shadow: 0 6rpx 16rpx rgba(0, 122, 255, 0.4);
	z-index: 99;
}
</style>
